package com.yc.web;

import com.yc.services.AddressService;
import com.yc.web.DTO.AddressDTO;
import com.yc.web.controller.model.ResponseResult;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
@Log
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 新增地址
     * POST /address/add
     * @param addressDTO 地址信息
     * @return 新增的地址信息
     */
    @PostMapping("/add")
    public ResponseEntity<ResponseResult> addAddress(@RequestBody AddressDTO addressDTO) {
        try {
            AddressDTO addedAddress = addressService.addAddress(addressDTO);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ResponseResult.ok("地址新增成功").setData(addedAddress));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("地址新增失败: " + e.getMessage()));
        }
    }

    /**
     * 更新地址
     * PUT /address/update
     * @param addressDTO 地址信息
     * @return 更新后的地址信息
     */
    @PutMapping("/update")
    public ResponseEntity<ResponseResult> updateAddress(@RequestBody AddressDTO addressDTO) {
        try {
            AddressDTO updatedAddress = addressService.updateAddress(addressDTO);
            return ResponseEntity.ok(ResponseResult.ok("地址更新成功").setData(updatedAddress));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("地址更新失败: " + e.getMessage()));
        }
    }

    /**
     * 删除地址（逻辑删除）
     * DELETE /address/delete/{addressId}
     * @param addressId 地址ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{addressId}")
    public ResponseEntity<ResponseResult> deleteAddress(
            @PathVariable Long addressId,
            @RequestParam Long userId) {
        try {
            boolean success = addressService.deleteAddress(addressId, userId);
            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("地址删除成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ResponseResult.error("地址不存在或删除失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("地址删除失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户地址列表
     * GET /address/list/{userId}
     * @param userId 用户ID
     * @return 地址列表
     */
    @GetMapping("/list/{userId}")
    public ResponseEntity<ResponseResult> getUserAddresses(@PathVariable Long userId) {
        try {
            List<AddressDTO> addresses = addressService.getUserAddresses(userId);
            return ResponseEntity.ok(ResponseResult.ok("获取地址列表成功").setData(addresses));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("获取地址列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取地址详情
     * GET /address/detail/{addressId}
     * @param addressId 地址ID
     * @param userId 用户ID
     * @return 地址详情
     */
    @GetMapping("/detail/{addressId}")
    public ResponseEntity<ResponseResult> getAddressDetail(
            @PathVariable Long addressId,
            @RequestParam Long userId) {
        try {
            AddressDTO address = addressService.getAddressDetail(addressId, userId);
            if (address != null) {
                return ResponseEntity.ok(ResponseResult.ok("获取地址详情成功").setData(address));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ResponseResult.error("地址不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("获取地址详情失败: " + e.getMessage()));
        }
    }

    /**
     * 设置默认地址
     * PUT /address/setDefault
     * @return 操作结果
     */
    @PutMapping("/setDefault")
    public ResponseEntity<ResponseResult> setDefaultAddress(
            @RequestBody Map<String, Long> params) {
        try {
            Long addressId = params.get("addressId");
            Long userId = params.get("userId");
            log.info("设置默认地址，addressId: "+addressId+", userId: "+ userId);

            boolean success = addressService.setDefaultAddress(addressId, userId);
            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("设置默认地址成功"));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(ResponseResult.error("设置默认地址失败"));
            }
        } catch (Exception e) {
            log.info("设置默认地址失败"+ e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("设置默认地址失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户默认地址ID
     * GET /address/default/{userId}
     * @param userId 用户ID
     * @return 默认地址ID
     */
    @GetMapping("/default/{userId}")
    public ResponseEntity<ResponseResult> getDefaultAddressId(@PathVariable Long userId) {
        try {
            Long addressId = addressService.getDefaultAddressId(userId);
            if (addressId != null) {
                return ResponseEntity.ok(ResponseResult.ok("获取默认地址ID成功").setData(addressId));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ResponseResult.error("用户没有设置默认地址"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("获取默认地址ID失败: " + e.getMessage()));
        }
    }
}